package gcontent.config;

import gcontent.config.error.ConfigEx;
import gcontent.config.persistents.node.ObjectNode;

import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PersistentConfig {
	
	public static final String PERSIS_CONF = "/persistents.xml";
	
	/* persistents */
	private static HashMap<String, ObjectNode> persistent_node = new HashMap<String, ObjectNode>();
	private static HashMap<String, ObjectNode> persistent_node_cls = new HashMap<String, ObjectNode>();
	
	public static void init() throws ConfigEx
	{
		InputStream in;
		
		in = PersistentConfig.class.getResourceAsStream(PERSIS_CONF);
		if(in == null)
			throw new ConfigEx("not found resource " + PERSIS_CONF + "!!");
		
		DocumentBuilderFactory dbfactory;
		DocumentBuilder builder; 
		Document doc;
		
		persistent_node.clear();

		try {
			NodeList node_list;
			
			dbfactory =  DocumentBuilderFactory.newInstance();
			builder = dbfactory.newDocumentBuilder();
			doc = builder.parse(in);
			node_list = doc.getDocumentElement().getChildNodes();
			
			for(int i = 0; node_list.item(i) != null; i++) {
				Node node;	
				String node_name;
				
				node = node_list.item(i);
				node_name = node.getNodeName();
				if(node_name.equals("object")) {
					ObjectNode obj_node;
					
					obj_node = new ObjectNode(node);
					persistent_node.put(obj_node.getId(), obj_node);
					persistent_node_cls.put(obj_node.getClassName(), obj_node);
					
				} else if(node_name.charAt(0) != '#')
					throw new ConfigEx("unknown node " + node_name);
			}
			
		} catch(ConfigEx ex) {
			throw ex;
			
		} catch(Exception ex) {
			throw new ConfigEx(ex);			
		}
	}
	
	public static ObjectNode getConf(String name)
	{
		return persistent_node.get(name);
	}
	
	public static ObjectNode getConfPerClass(String clsname)
	{	
		return persistent_node_cls.get(clsname);
	}

}
